<template>
    <ContentBase>
        <div id="form-container1" class="container text-center">
            <ContentBase>
                <h5>联合搜索</h5>
                <form id="search-form" class="d-flex justify-content-center" role="search" @submit.prevent="search">
                    <div class="form-group mx-2">
                        <label for="filename">文件名：</label>
                        <input class="form-control" type="text" id="filename" placeholder="不限文件名" v-model="filename">
                    </div>
                    <div class="form-group mx-2">
                        <label for="major">专业：</label>
                        <input class="form-control" type="text" id="major" placeholder="不限专业" v-model="major">
                    </div>
                    <div class="form-group mx-2">
                        <label for="subject">学科：</label>
                        <input class="form-control" type="text" id="subject" placeholder="不限学科" v-model="subject">
                    </div>
                    <div class="form-group mx-2">
                        <label for="uploader">上传者：</label>
                        <input class="form-control" type="text" id="uploader" placeholder="不限上传者" v-model="uploader">
                    </div>
                    <button style="height:20%; width:5%;margin-top:24px ;" class="btn btn-primary" type="submit">搜索</button>
                    <button style="height:20%; width:5%;margin-top:24px; " class="btn btn-success mx-2" type="button"
                        @click="reset">重置</button>
                </form>
                <ContentBase>
                    <h5>数据筛选</h5>
                    <div class="d-flex justify-content-center">
                        <div class="row">
                            <div class="col">
                                <label>年级：</label>
                                <select class="form-select" aria-label="Default select example" v-model="selectedGrade">
                                    <option value="">不限年级</option>
                                    <option value="1">大一</option>
                                    <option value="2">大二</option>
                                    <option value="3">大三</option>
                                    <option value="4">大四</option>
                                </select>
                            </div>
                            <div class="col">
                                <label>年份：</label>
                                <select class="form-select" aria-label="Default select example" v-model="selectedYear">
                                    <option value="">不限年份</option>
                                    <option v-for="year in years" :value="year" :key="year">{{ year }}</option>
                                </select>
                            </div>
                            <div class="col">
                                <label>文件描述：</label>
                                <select class="form-select" aria-label="Default select example"
                                    v-model="selectedDecription">
                                    <option value="">不限描述</option>
                                    <option v-for="description in descriptions" :value="description" :key="description">{{
                                        description }}
                                    </option>
                                </select>
                            </div>

                        </div>
                    </div>
                </ContentBase>
            </ContentBase>


            <ContentBase>
                <div class="row">
                    <div class="col">
                        文件名
                    </div>
                    <div class="col">
                        专业
                    </div>
                    <div class="col">
                        学科
                    </div>
                    <div class="col">
                        文件大小
                    </div>
                    <div class="col">
                        上传者
                    </div>
                    <div class="col">
                        上传时间
                    </div>
                    <div class="col">
                        描述
                    </div>
                    <div class="col">
                        下载
                    </div>
                </div>
            </ContentBase>
            <ContentBase>
                <div id="form-container" class="container text-center">
                </div>

            </ContentBase>
        </div>
    </ContentBase>
</template>
<script>
import ContentBase from '../components/ContentBase.vue';
import $ from 'jquery';
export default {
    name: 'UserListView',
    components: {
        ContentBase,
    }, data() {
        return {
            //返回的文件列表
            resp: [],
            //输入框内的值
            filename: '',
            major: '',
            subject: '',
            uploader: '',
            selectedGrade: '', // 选中的年级
            selectedYear: '', // 选中的年份
            selectedDecription: '',//选中的描述
            startYear: 2000, // 起始年份
            endYear: 2023, // 结束年份
            years: [], // 年份选项列表
            descriptions: []
        };
    },
    methods: {
        generateYearOptions() {
            const years = [];
            for (let year = this.endYear; year >= this.startYear; year--) {
                years.push(year);
            }
            this.years = years;
        },
        fetchDescriptions() {// 发起获取所有描述的 Ajax 请求
            $.ajax({
                url: 'http://10.142.225.1:3000/file/descriptions',
                method: 'get',
                success: (resp) => {
                    this.descriptions = resp;
                },
                error: () => {
                    alert("失败！");
                }
            });
        },
        search() {
            /*
            this.filename = this.filename.trim();
            this.major = this.major.trim();
            this.subject = this.subject.trim();
            this.uploader = this.uploader.trim();
            去除前后多余的空格
            */
            $.ajax({
                url: 'http://10.142.225.1:3000/file/search', //获取所有文件信息的服务器接口
                method: 'POST',
                data: {
                    filename: this.filename,
                    major: this.major,
                    subject: this.subject,
                    uploader: this.uploader
                },
                success: (resp) => {
                    this.resp = resp;
                    this.renderFormData(resp);
                },
                error: () => {
                    alert("搜索失败！");
                }
            });
        },
        reset() {
            this.filename = '';
            this.major = '';
            this.subject = '';
            this.uploader = '';
        },
        renderFormData(resp) {
            if (localStorage.getItem("is_login") != "true") {
                if (formContainer) {
                    formContainer.innerHTML = ''; // 清空容器内容
                    var message = document.createElement('div'); // 创建列，文件名
                    message.className = "col";
                    message.textContent = "您尚未登录，点击右上角登录/注册账户"; //写入
                    formContainer.appendChild(message);
                }
            }
            else
                if (resp != null) {
                    var formData = this.resp;
                    // 创建表单容器
                    var formBox = document.createElement("div"); //创建展示框
                    for (var i = 0; i < formData.length; i++)
                        if (this.selectedGrade == '' || this.selectedGrade == formData[i].grade)
                            if (this.selectedYear == '' || this.selectedYear == formData[i].year)
                                if (this.selectedDecription == '' || this.selectedDecription == formData[i].description) {
                                    var formRow = document.createElement('div'); //创建行
                                    formRow.className = "row";
                                    var filename = document.createElement('div'); // 创建列，文件名
                                    filename.className = "col";
                                    filename.textContent = formData[i].filename; //写入
                                    var major = document.createElement('div'); // 创建列，专业
                                    major.className = "col";
                                    major.textContent = formData[i].majorid; //写入
                                    var subject = document.createElement('div'); // 创建列，学科
                                    subject.className = "col";
                                    subject.textContent = formData[i].subject; //写入
                                    var size = document.createElement('div'); // 创建列，大小
                                    size.className = "col";
                                    size.textContent = formData[i].size; //写入
                                    var author = document.createElement('div'); // 创建列，作者
                                    author.className = "col";
                                    author.textContent = formData[i].author; //写入
                                    var updatedate = document.createElement('div'); // 创建列，上传时间
                                    updatedate.className = "col";
                                    var description = document.createElement('div'); // 创建列，描述
                                    description.className = "col";
                                    description.textContent = formData[i].description
                                    var date = new Date(formData[i].updatedate);
                                    // 指定日期格式
                                    var options = {
                                        year: 'numeric',
                                        month: '2-digit',
                                        day: '2-digit',
                                        hour: '2-digit',
                                        minute: '2-digit',
                                        second: '2-digit',
                                    };
                                    // 使用 toLocaleString() 方法将日期对象格式化为特定格式的字符串
                                    var formattedDate = date.toLocaleString('zh-CN', options);
                                    updatedate.textContent = formattedDate; //写入
                                    var downloadButton = document.createElement('button'); // 创建下载按钮
                                    downloadButton.classList.add('col', 'downloadbutton'); // 添加列类和自定义按钮类
                                    downloadButton.setAttribute('type', 'downloadbutton');
                                    downloadButton.id = 'button_' + i;
                                    //console.log(downloadButton.id);
                                    downloadButton.textContent = "下载"; // 设置按钮文本内容
                                    downloadButton.onclick = (function close(j) {//闭包函数在声明后就立刻执行
                                        //不使用闭包函数则会让所有按钮都指向最后一个i值！！！
                                        return function () {
                                            //console.log("下载第" + (j + 1) + "个文件");
                                            var urlString = 'http://10.142.225.1:3000/file/download/' + formData[j].filename;
                                            //console.log(urlString);
                                            window.open(urlString, "_self");
                                        }
                                    })(i);
                                    formRow.appendChild(filename);
                                    formRow.appendChild(major);
                                    formRow.appendChild(subject);
                                    formRow.appendChild(size);
                                    formRow.appendChild(author);
                                    formRow.appendChild(updatedate);
                                    formRow.appendChild(description);
                                    formRow.appendChild(downloadButton);
                                    formBox.appendChild(formRow); // 将表单行添加到表单容器中
                                }
                    // 将表单容器添加到文档中的特定位置
                    var formContainer = document.getElementById('form-container');
                    if (formContainer) {
                        formContainer.innerHTML = ''; // 清空容器内容
                        formContainer.appendChild(formBox);
                    }

                }
        }
    },
    mounted() {
        // 生成年份选项列表
        this.generateYearOptions();
        // 生成描述选项列表
        this.fetchDescriptions();
        if (localStorage.getItem("is_login") != "true") {
            var formContainer = document.getElementById('form-container');
            var formBox = document.createElement("div"); //创建展示框
            var blank = document.createElement('div'); // 创建列，专业
            blank.className = "col";
            blank.textContent = "您尚未登录"; //写入
            formBox.append(blank);
            if (formContainer) {
                formContainer.appendChild(formBox);
            }
        } else
            $.ajax({
                url: 'http://10.142.225.1:3000/file/all', //获取所有文件信息的服务器接口
                method: 'GET',
                success: (resp) => {
                    this.resp = resp;
                    this.renderFormData(resp);
                },
                error: () => {
                    alert("下载失败！");
                }
            });
        this.filename = localStorage.getItem("SearchKey"); //获取主页传过来的搜索值
        this.search(); //搜索
        this.renderFormData(); //绘制表单
        localStorage.setItem("SearchKey", ""); //清空

    }

}   
</script>
  
<style >
.downloadbutton {
    width: auto;
    margin-top: 0px;
    margin-bottom: 2px;
    background-color: lightcyan;
    outline: none;
    border-radius: 8px;
    padding: 13px;
    color: gray;
    letter-spacing: 2px;
    border: none;
    cursor: pointer;
}

.downloadbutton:hover {
    background-color: rgb(64, 191, 191);
    color: lightcyan;
    transition: background-color 0.5s ease;
}
</style>
    